package admin_rule_dao

import (
	"fmt"
	admin_rule_types "oc_saas/internal/app/api/admin/rule/types"
	"oc_saas/internal/model/base"
	"oc_saas/internal/model/share"
	oc_types "oc_saas/internal/types"

	"gorm.io/gorm"
)

// 处理添加规则时传过来的结构体
func OperaRuleStructWhenAddRule(db *gorm.DB, data *admin_rule_types.Rule) *share.Rule {
	var parentRule *share.Rule
	var pid uint
	if data.PID == 0 {
		pid = 1
	}
	if err := db.Select("link,id").First(&parentRule, pid).Error; err != nil {
		panic(&oc_types.CustomError{Msg: oc_types.RULE_NOT_FOUND, Error: err.Error()})
	}
	var link = fmt.Sprintf("%v%v,", parentRule.Link, parentRule.ID)
	var newData = &share.Rule{
		Name:       data.Name,
		PID:        pid,
		Perms:      data.Perms,
		Link:       link,
		Type:       data.Type,
		SortColumn: base.SortColumn{Sort: data.Sort},
	}
	if data.Type == share.MENU {
		newData.Route = &share.Route{
			Name:        data.Route.Name,
			Path:        data.Route.Path,
			Component:   data.Route.Component,
			Icon:        data.Route.Meta.Icon,
			Title:       data.Route.Meta.Title,
			IsLink:      data.Route.Meta.IsLink,
			IsHide:      data.Route.Meta.IsHide,
			IsFull:      data.Route.Meta.IsFull,
			IsAffix:     data.Route.Meta.IsAffix,
			IsKeepAlive: data.Route.Meta.IsKeepAlive,
			Redirect:    data.Route.Redirect,
			IsHome:      data.Route.IsHome,
		}
	} else {
		newData.Api = &share.Api{
			Type: data.Api.Type,
			Path: data.Api.Path,
		}
	}

	return newData
}

// 规则树搜索scope
func RuleTreeSearchDao(rule_type string, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if rule_type == "" {
			return db
		} else {
			return db.Where("r.type = ?", rule_type)
		}
	}
}

// 转化规则树返回前端
func TransRuleTreeDao(daoList []*admin_rule_types.RuleBody) []*share.Rule {
	var newList = make([]*share.Rule, 0)
	for _, v := range daoList {
		var newItem = &share.Rule{
			Name:       v.Name,
			Perms:      v.Perms,
			Type:       v.Type,
			SortColumn: base.SortColumn{Sort: v.Sort},
			IDColumn:   base.IDColumn{ID: v.ID},
		}
		if v.Type == "MENU" {
			var route = &share.Route{
				Name:        v.Perms,
				Component:   v.Component,
				Redirect:    v.Redirect,
				IsHome:      v.IsHome,
				Path:        v.Path,
				Icon:        v.Icon,
				Title:       v.Title,
				IsLink:      v.IsLink,
				IsHide:      v.IsHide,
				IsFull:      v.IsFull,
				IsAffix:     v.IsAffix,
				IsKeepAlive: v.IsKeepAlive,
			}
			newItem.Route = route
		} else if v.Type == "REQ" {
			var api = &share.Api{
				Path: v.ApiPath,
				Type: v.ApiType,
			}
			newItem.Api = api
		}
		newList = append(newList, newItem)
	}
	return newList
}
